package com.evil.common.log.util;

import com.evil.common.core.util.ServletUtils;
import com.evil.common.log.constant.LogConstant;
import com.evil.common.redis.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

/**
 * @author liyang
 * @date 2022-08-08 00:00
 */
public class LogUtil {

    public static String interceptContent(String content) {
        if (StringUtils.isBlank(content)) {
            return content;
        }

        if (content.length() > LogConstant.MAX_LOG_CHARACTER_LENGTH) {
            content = content.substring(0, LogConstant.MAX_LOG_CHARACTER_LENGTH);
        }
        return content;
    }

    /**
     * 获取请求日志ID
     *
     * @param redisUtil redisUtil
     * @return String
     */
    public static String getRequestLogId(RedisUtil redisUtil) {
        return Optional.ofNullable(redisUtil.get(LogRedisKeyUtil.requestUuidRequestLogId()))
                .map(e -> (String) e)
                .orElseGet(() -> ServletUtils.getRequest().getHeader(LogConstant.HEADER_REQUEST_LOG_ID));
    }

    /**
     * 接口处理时长
     *
     * @param handleTime handleTime
     * @return String
     */
    public static String handleTime(long handleTime) {
        int second = handleTime > 10000L ? 10 : (handleTime > 6000L ? 6 : (handleTime > 3000L ? 3 : 0));
        return second == 0 ? "" : String.format(" | 接口响应时间超过%s秒", second);
    }
}
